package com.example.config.filter;

import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
import io.micronaut.http.MutableHttpResponse;
import io.micronaut.http.annotation.Filter;
import io.micronaut.http.filter.HttpServerFilter;
import io.micronaut.http.filter.ServerFilterChain;
import io.micronaut.http.filter.ServerFilterPhase;
import io.micronaut.json.tree.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.slf4j.MDC;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author ：FuXx
 * @className : com.example.filter.AuthFilter
 * @since ：2025/7/17
 */
@Slf4j
@Filter(Filter.MATCH_ALL_PATTERN)
public class AuthFilter implements HttpServerFilter {

    @Override
    public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) {
        MDC.put("requestId", UUID.randomUUID().toString());
        String token = request.mutate().getHeaders().get("Authorization");
        log.info(request.getPath());
        if (token == null) {
            return responseError("未登录");
        }
        Publisher<MutableHttpResponse<?>> proceed = chain.proceed(request);
        MDC.remove("requestId");
        return proceed;
    }

    private Mono<MutableHttpResponse<?>> responseError(String message) {
        MDC.remove("requestId");
        return Mono.just(HttpResponse.status(HttpStatus.UNAUTHORIZED)
                .contentType(MediaType.APPLICATION_JSON_TYPE)
                .characterEncoding(MediaType.APPLICATION_JSON_TYPE.getCharset().orElse(StandardCharsets.UTF_8))
                .body(JsonObject.createStringNode(message)));
    }

    @Override
    public int getOrder() {
        return ServerFilterPhase.SECURITY.order();
    }

}
